/*
 * WordPress版同城信息发布
 * author: huangbin
 * 技术支持微信号：wxid_i8yk4fp0uep322
 * 开源协议：MIT
 *  *Copyright (c) 2018 https:/www.tczhb.club All rights reserved.
 */

var Api = require('../../utils/api.js');
var util = require('../../utils/util.js');
var WxParse = require('../../wxParse/wxParse.js');
var wxApi = require('../../utils/wxApi.js')
var wxRequest = require('../../utils/wxRequest.js')

var app = getApp();
var pageCount = app.globalData.page_size ? app.globalData.page_size : 5;

Page({
  data: {
    title: '文章列表',
    postsList: {},
    pagesList: {},
    categoriesList: {},
    postsShowSwiperList: {},
    isLastPage: false,
    page: 1,
    search: '',
    categories: 0,
    categoriesName:'',
    categoriesImage:"", 
    showerror:"none",
    isCategoryPage:"none",
    isSearchPage:"none",
    showallDisplay: "block",
    displaySwiper: "block",
    floatDisplay: "none",
    searchKey:"",
    author:0,
    include:"",
    isMy:false,
  },
  formSubmit: function (e) {
    var url = '../list/list'
    if (e.detail.value.input != '') {
      url = url + '?search=' + e.detail.value.input;
    }
    wx.navigateTo({
      url: url
    })
  },
  onShareAppMessage: function () {

    var title = "分享“守望轩”";
    var path =""

    if (this.data.categories && this.data.categories != 0)
  {
      title += "的专题：" + this.data.categoriesList.name;
      path = 'pages/list/list?categoryID=' + this.data.categoriesList.id;

  }
  else
  {
      title += "的搜索内容：" + this.data.searchKey;
      path = 'pages/list/list?search=' + this.data.searchKey;
  }


    return {
      title: title,
      path: path,
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  reload:function(e)
  {
    var self = this;
    if (self.data.categories && self.data.categories != 0) {
      
      self.setData({
       // categories: options.categoryID,
        isCategoryPage: "block",
        showallDisplay: "none",
        showerror: "none",

      });
      self.fetchCategoriesData(self.data.categories);
    }
    if (self.data.search && self.data.search != '') {
      self.setData({
        //search: options.search,
        isSearchPage: "block",
        showallDisplay: "none",
        showerror: "none",
        searchKey: self.data.search
      })
    }
    self.fetchPostsData(self.data);
  },
  //加载分页
  loadMore: function (e) {
    var self = this;
    if (!self.data.isLastPage) {
      self.setData({
        page: self.data.page + 1
      });
      console.log('当前页' + self.data.page);
      this.fetchPostsData(self.data);
    }
  },
  onLoad: function (options) {
    var self = this;
    if (options.categoryID && options.categoryID != 0) {
      self.setData({
        categories: options.categoryID,
        isCategoryPage:"block"
      });
      self.fetchCategoriesData(options.categoryID);
    }
    if (options.search && options.search != '') {
      wx.setNavigationBarTitle({
        title: "搜索关键字："+options.search,
        success: function (res) {
          // success
        }
      });
      self.setData({
        search: options.search,
        isSearchPage:"block",
        searchKey: options.search
      })
      this.fetchPostsData(self.data);
    }
    if (options.list_type && options.list_type != '') {
      var barTitle = "";
      //我发布的
      if (options.list_type == "myPublish"){
        barTitle = "我发布的";
        self.setData({
          author: app.globalData.uid,
          isMy: true
        })
      }
      //我浏览的
      if (options.list_type == "myView"){
        barTitle = "我浏览的";
        var include_id = (wx.getStorageSync('readLogs') || []).map(function (log) {
          return log[0];
        })
        var include_id_str = "";
        if (include_id.length > 0){
          include_id_str = include_id.toString();
        }else{
          include_id_str = "0";
        }
        self.setData({
          include: include_id_str
        })
      }
      //我点赞的
      if (options.list_type == "myLikes"){
        barTitle = "我点赞的";
        var openid = app.globalData.openid;
        var getMylikePosts = wxRequest.getRequest(Api.getMyLikeUrl(openid));
        getMylikePosts.then(response => {
          if (response.statusCode == 200) {
            var include_id = response.data.data.map(function (item) {
              return item.post_id;
            })
            var include_id_str = "";
            if (include_id.length > 0) {
              include_id_str = include_id.toString();
            } else {
              include_id_str = "0";
            }
            self.setData({
              include: include_id_str
            })
            this.fetchPostsData(self.data);
          }
        })
      }
      //我评论的
      if (options.list_type == "myComment"){
        barTitle = "我评论的";
        var openid = app.globalData.openid;
        var getMyCommentsPosts = wxRequest.getRequest(Api.getWeixinComment(openid));
        getMyCommentsPosts.then(response => {
          if (response.statusCode == 200) {
            var include_id = response.data.data.map(function (item) {
              return item.post_id;
            })
            var include_id_str = "";
            if (include_id.length > 0) {
              include_id_str = include_id.toString();
            } else {
              include_id_str = "0";
            }
            self.setData({
              include: include_id_str
            })
            this.fetchPostsData(self.data);
          }
        })
      }
      wx.setNavigationBarTitle({
        title: barTitle
      })
      if (!options.list_type || (options.list_type != "myLikes" && options.list_type != "myComment")){
        this.fetchPostsData(self.data);
      }
    }
  },
  //获取文章列表数据
  fetchPostsData: function (data) {
    var self = this;  
    if (!data) data = {};
    if (!data.page) data.page = 1;
    if (!data.categories) data.categories = 0;
    if (!data.search) data.search = '';
    data.author_exclude = 1;
    if (data.page === 1) {
      self.setData({
        postsList: []
      });
    };
    
    wx.showLoading({
      title: '正在加载',
      mask:true
    });

    var getPostsRequest = wxRequest.getRequest(Api.getPosts(data));

    getPostsRequest.then(response =>{

        if (response.statusCode === 200) {
          if (response.data.data.length < pageCount) {
                self.setData({
                    isLastPage: true
                });
            };
          if (response.data.data.length > 0){
            self.setData({
              floatDisplay: "block"
            })
          }
            self.setData({
                //floatDisplay: "block",
                showallDisplay: "block",
                postsList: self.data.postsList.concat(response.data.data.map(function (item) {
                    var strdate = item.published_time
                    item.dateStr = util.getDateDiff(strdate);
                    item.post_content = util.removeHTML(item.post_content);
                    if(self.data.isMy){
                      item.isMy = true;
                    }
                    return item;
                })),
            });
        }
        else {
            if (response.data.code == "rest_post_invalid_page_number") {
                self.setData({
                    isLastPage: true
                });
            }
            else {
                wx.showToast({
                    title: response.data.message,
                    duration: 1500
                })
            }
        }   
    })
    .catch(function(){        
        if (data.page == 1) {
            self.setData({
                showerror: "block",
                floatDisplay: "none"
            });
        }
        else {
          wx.showModal({
              title: '加载失败',
              content: '加载数据失败,请重试.',
              showCancel: false,
          });
          self.setData({
            page: data.page - 1
          });
        }
    })
    .finally(function () {
        wx.hideLoading();
    })  
  },  



  // 跳转至查看文章详情
  redictDetail: function (e) {
    // console.log('查看文章');
    var id = e.currentTarget.id,
      url = '../detail/detail?id=' + id;
    wx.navigateTo({
      url: url
    })
  },

  //获取分类列表
  fetchCategoriesData: function (id) {
    var self = this;
    self.setData({
      categoriesList: []
    });
    var getCategoryRequest = wxRequest.getRequest(Api.getCategoryById(id));
    getCategoryRequest.then(response =>{
      self.setData({
        categoriesList: response.data.data,
        categoriesName: response.data.data.name
      });
      wx.setNavigationBarTitle({
        title: response.data.data.name,
        success: function (res) {
            // success
        }
      });
      self.fetchPostsData(self.data); 
    })
  },
  //图片预览
  previewImage: function (e) {
    var that = this;
    var imgs = e.currentTarget.dataset.imgs;
    var urls = [];
    for (var i = 0, len = imgs.length; i < len; i++) {
      urls.push(imgs[i]['url']);
    }
    wx.previewImage({
      current: e.currentTarget.dataset.img,
      urls: urls
    })
  },
  /**
  * 打开地图标注
  */
  open_map: function (e) {
    //console.log(e.currentTarget.dataset)
    var lat = e.currentTarget.dataset.lat;
    var lon = e.currentTarget.dataset.lon;
    if (lat != '0') {
      wx.openLocation({
        latitude: parseFloat(lat),
        longitude: parseFloat(lon),
        scale: 28
      });
    } else {
      wx.showToast({
        image: '../../resource/images/static/error.png',
        title: '座标错误,无法定位!',
      });
    }
  },
  /**
 * 联系他
 */
  tap_phone: function (e) {
    var phone = e.currentTarget.dataset.uphone;
    wx.makePhoneCall({ phoneNumber: phone });
  },
  /** 
   * 删除信息
  */
  tap_delete: function(e){
    Array.prototype.delete = function (delIndex) { 
      var temArray = []; 
      for (var i = 0; i < this.length; i++) { 
        if (this[i].id != delIndex) { temArray.push(this[i]) } 
      } 
      return temArray ;
    }
    var id = e.currentTarget.dataset.id;
    var that = this;
    wx.showModal({
      title: '提示',
      content: '是否删除?',
      success: function (res) {
        if (res.confirm) {
          var deleteUrl = Api.deletePost();   //接口url
          var data = {
            id:id
          }
          wx.showLoading({
            title: '正在删除中...',
            mask: true
          });
          var postDeleteRequest = wxRequest.postRequest(deleteUrl, data);
          postDeleteRequest.then(res => {
            if (res.statusCode == 200) {
              wx.hideLoading();
              var list_t = that.data.postsList;
              list_t = list_t.delete(id);
              that.setData({ postsList: list_t });
            }
            wx.hideLoading();
          })
        }
      }
    })
  },
  onReachBottom:function () {
    var self = this;
    this.loadMore();
  }
})



